import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_theme_colors.dart';

/// 图片容器
class KqHeadImageBox extends StatefulWidget {
  /// 列数，默认4
  final int cols;

  /// 最大图片容量，默认8
  final int maxQty;

  /// 图片之间的间距，默认10
  final double? spacing;

  ///当前选中的
  final int chooseIndex;

  /// 图片类型和路径
  final List<ImageUrl> urls;

  /// 能否编辑，不能编辑则不显示删除和添加按钮，默认true
  final bool editable;

  /// 自定义添加按钮图片
  final String? customAddPic;

  /// 图片数量变化回调
  final Function()? onChanged;

  /// 图片添加按钮点击回调
  final Function(List<ImageUrl> urls, KqHeadImageBoxState state)? onAddTap;

  /// 图片点击回调
  final Function(List<ImageUrl> urls, ImageUrl imageUrl, int position,
      KqHeadImageBoxState state)? onImageTap;

  const KqHeadImageBox(
      {Key? key,
      required this.urls,
      this.onAddTap,
      this.onImageTap,
      this.spacing,
      this.cols = 4,
      this.maxQty = 8,
      this.customAddPic,
      this.editable = true,
      this.onChanged,
      this.chooseIndex = 0})
      : super(key: key);

  @override
  KqHeadImageBoxState createState() => KqHeadImageBoxState();
}

class KqHeadImageBoxState extends State<KqHeadImageBox> {
  /// 刷新
  void update() {
    setState(() {});
    if (widget.onChanged != null) {
      widget.onChanged!();
    }
  }

  /// 图片数量
  int count() {
    return widget.urls.length;
  }

  /// 添加图片
  void addImage(ImageUrl imageUrl) {
    if (widget.maxQty != 0 && widget.urls.length >= widget.maxQty) {
      return;
    }
    widget.urls.add(imageUrl);
    update();
  }

  /// 拼接提交的url
  String? getSubmitUrls({join = ','}) {
    if (widget.urls.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.urls) {
      values.add(url.url);
    }
    return values.isEmpty ? null : values.join(join);
  }

  /// 拼接提交的valueForSubmit
  String? getSubmitValues({join = ','}) {
    if (widget.urls.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.urls) {
      if (url.valueForSubmit != null) {
        values.add(url.valueForSubmit);
      }
    }
    return values.isEmpty ? null : values.join(join);
  }

  /// 删除图片
  void remove(ImageUrl imageUrl) {
    widget.urls.remove(imageUrl);
    update();
  }

  List<Widget> _buildImages() {
    var imageCount = 0;
    List<Widget> list = [];
    imageCount = widget.urls.length;
    for (int i = 0; i < imageCount; i++) {
      ImageUrl imageUrl = widget.urls[i];
      list.add(_buildImageItem(imageUrl, i));
    }
    if (imageCount < widget.maxQty && widget.editable) {
      list.add(
        _buildImageItem(
            ImageUrl(
                imageType: ImageType.assets,
                url: widget.customAddPic ?? Images.commonPicUpload88,
                uploadOk: true,
                isAddBtn: true,
                package: KqGlobal.packageName),
            imageCount),
      );
    }
    return list;
  }

  /// 图片或新增按钮
  Widget _buildImageItem(ImageUrl imageUrl, int position) {
    return KqInkWell(
      onTap: () {
        if (imageUrl.isAddBtn) {
          if (widget.onAddTap != null) {
            widget.onAddTap!(widget.urls, this);
          }
        } else {
          if (widget.onImageTap != null) {
            widget.onImageTap!(widget.urls, imageUrl, position, this);
          }
        }
      },
      child: widget.chooseIndex == position
          ? Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(2.r)),
                  border: Border.all(
                      color: KqThemeColors.textLightBlue, width: 2.r)),
              child: _buildImage(imageUrl),
            )
          : _buildImage(imageUrl),
    );
  }

  double widgetWidth = 0;

  /// 每张图片大小DD
  double imageSize = 0;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        var spacing = widget.spacing ?? 10.r;
        widgetWidth = constraints.maxWidth;
        imageSize = (widgetWidth - spacing * (widget.cols - 1)) / widget.cols;
        return GridView.count(
          crossAxisCount: widget.cols,
          shrinkWrap: true,
          padding: EdgeInsets.zero,
          physics: const NeverScrollableScrollPhysics(),
          mainAxisSpacing: spacing,
          crossAxisSpacing: spacing,
          //宽高比
          childAspectRatio: 1 / 1,
          children: _buildImages(),
        );
      },
    );
  }

  Widget _buildImage(ImageUrl imageUrl) {
    if (imageUrl.imageType == ImageType.oss) {
      return KqImage.oss(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: BoxFit.cover,
        package: imageUrl.package,
      );
    } else if (imageUrl.imageType == ImageType.http) {
      return KqImage.http(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: BoxFit.cover,
        package: imageUrl.package,
      );
    } else if (imageUrl.imageType == ImageType.file) {
      return KqImage.file(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: BoxFit.cover,
        package: imageUrl.package,
      );
    } else {
      return KqImage.assets(
        width: imageSize,
        height: imageSize,
        url: imageUrl.url,
        placeHolder: imageUrl.placeHolder,
        errorImage: imageUrl.placeHolder,
        fit: BoxFit.cover,
        package: imageUrl.package,
      );
    }
  }
}
